package com.my.house.controller;


import com.my.house.common.ApiResult;
import com.my.house.common.utils.ThreadLocalHolder;
import com.my.house.domain.User;
import com.my.house.vo.RoomReqVO;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import com.my.house.domain.Room;
 import com.my.house.service.RoomService;

import java.util.List;

/**
 * <p>
 * 用户楼栋房间表 前端控制器
 * </p>
 *
 * @author yangll
 * @since 2025-02-08
 */
@Slf4j
@RestController
@RequestMapping("/api/room")
public class RoomController {
    @Autowired
    private RoomService roomService;

    @GetMapping("/list")
    public ApiResult<List<Room>> list(Long buildingId) {
        log.info("/building/list");
        User user = ThreadLocalHolder.getUser();
        assert user != null;
        return ApiResult.ok(roomService.findByBuildingId(user.getId(), buildingId));
    }

    @PostMapping("addRoom")
    public ApiResult<Void> addRoom(@RequestBody @Validated RoomReqVO reqVO) {
        User user = ThreadLocalHolder.getUser();
        assert user != null;
        roomService.addRoom(user.getId(), reqVO.getBuildingId(), reqVO.getName(), reqVO.getWaterNum(), reqVO.getElectricNum());
        return ApiResult.ok();
    }

    @PostMapping("editRoom")
    public ApiResult<Void> editRoom(@RequestBody @Validated RoomReqVO reqVO) {
        User user = ThreadLocalHolder.getUser();
        assert user != null;
        Assert.notNull(reqVO.getId(), "id不能为空");
        roomService.editRoomById(reqVO.getId(), reqVO.getBuildingId(), reqVO.getName(), reqVO.getWaterNum(), reqVO.getElectricNum(), user.getId());
        return ApiResult.ok();
    }

    @GetMapping("/getById")
    public ApiResult<Room> getById(Long id) {
        log.info("/room/getById, id={}", id);
        User user = ThreadLocalHolder.getUser();
        assert user != null;
        Room room = roomService.lambdaQuery()
                .eq(Room::getId, id)
                .eq(Room::getUserId, user.getId())
                .eq(Room::getDeleted, Boolean.FALSE)
                .one();
        return ApiResult.ok(room);
    }

    @PostMapping("delRoom")
    public ApiResult<Void> delRoom(@RequestBody Long id) {
        User user = ThreadLocalHolder.getUser();
        assert user != null;
        Assert.notNull(id, "id不能为空");
        roomService.deleteRoomById(user.getId(), id);
        return ApiResult.ok();
    }
}
